import React, { useEffect, useRef, useState } from 'react'
import { Button, Checkbox, Input, InputNumber, message, Modal, Radio, Space, Steps, Typography } from 'antd'
import PageContainer from '@/components/PageContainer'
import { usePakingColumns } from './columns'
import CustomTable from '@/components/CustomTable'
import { useNavigate, useSearchParams } from 'react-router-dom'
import './Packing.less'
import { scanAndGetInfo, scanAndPacking, tempSaveBoxPaking } from '@/api/purchase'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import WarningAudio from '@/assets/mp3/warning.mp3'
import SuccessAudio from '@/assets/mp3/success.mp3'
import { useAppSelector } from '@/store/hooks'
let audioWarning: any = null
let audioSuccess: any = null
const Index: React.FC = () => {
  const [query] = useSearchParams()
  const boxLabelId = query.get('boxLabelId')
  const [currentStep, setcurrentStep] = useState(0)
  const renderItem = () => {
    if (!boxLabelId) {
      return (
        <div className="purchase_packing_page">
          <div className="step_wrap_box">
            <Steps
              current={currentStep}
              items={[
                {
                  title: '扫描箱唛条码',
                },
                {
                  title: '扫描商品',
                },
              ]}
            />
          </div>
          {currentStep === 0 ? <PackingNumber></PackingNumber> : <Main></Main>}
        </div>
      )
    } else {
      return <Main></Main>
    }
  }
  return renderItem()
}

export default Index

function Main() {
  const [scannedQty, setscannedQty] = useState<number>(1)
  const [preQty, setpreQty] = useState<number>(2)
  const [hasScanPreQty, sethasScanPreQty] = useState<number>(0)
  const [isshow, setisshow] = useState(false)
  const [ismanyshow, setismanyshow] = useState(false)
  const [hasVoice, sethasVoice] = useState(true)
  const [hasError, sethasError] = useState(true)
  const [inputValue, setinputValue] = useState('')
  const [query] = useSearchParams()
  const boxLabelId = query.get('boxLabelId')
  const boxLabelCode = query.get('boxLabelCode')
  const from = query.get('from')
  const [details, setDetail] = useState<Record<string, any>>({ boxLabelId: 1 })
  const navigate = useNavigate()
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const [radioOptions, setradioOptions] = useState<IOptionItem[]>([])
  const [defaultKey, setdefaultKey] = useState('')
  const inputRef = useRef<any>(null)
  useEffect(() => {
    const items: IOptionItem[] = []
    if (buttonCodeList.includes('OneByOne')) {
      setdefaultKey('OneByOne')
      items.push({
        label: '逐件扫码',
        value: 'OneByOne',
      })
    }
    if (buttonCodeList.includes('PointScan')) {
      items.length === 0 && setdefaultKey('PointScan')
      items.length === 0 && setisshow(true)
      items.push({
        label: '点数扫码',
        value: 'PointScan',
      })
    }
    if (buttonCodeList.includes('MultiCodeScan')) {
      items.length === 0 && setdefaultKey('MultiCodeScan')
      items.length === 0 && setismanyshow(true)
      items.push({
        label: '一件多码',
        value: 'MultiCodeScan',
      })
    }
    setradioOptions(items)
    if (!audioWarning) {
      audioWarning = document.createElement('audio')
      audioWarning.src = WarningAudio
      audioWarning.load()
    }
    if (!audioSuccess) {
      audioSuccess = document.createElement('audio')
      audioSuccess.src = SuccessAudio
      audioSuccess.load()
    }
    getDetail()
  }, [])
  const getDetail = async () => {
    const res = await scanAndGetInfo<Record<string, any>>(boxLabelCode)
    setDetail(res.data)
    if (res.data.boxLabelStatus === 1) return
    checkIsOver(res.data)
    return res.data
  }
  const handleInputChange = (event: any) => {
    console.log(event.target.value, 'event.target.value')
    setinputValue(event.target.value)
  }
  const handleSaveToList = async (flag: boolean) => {
    if (radioOptions.length === 0) {
      setinputValue('')
      message.warning('当前页面未配置逐件扫码、点数扫码、一件多码按钮权限！')
      return
    }
    // flag 区分是暂存true 还是 扫码中
    if (details.boxLabelStatus === 1) {
      setinputValue('')
      message.warning('该箱唛已装箱不支持修改')
      return
    }
    if (!flag && details.skuCode != inputValue) {
      //扫码中不是暂存状态
      setinputValue('')
      audioWarning.currentTime = 0
      hasVoice && audioWarning.play()
      if (!hasError) {
        message.warning(
          <div>
            <div style={{ textAlign: 'left' }}>商品条码不一致，请检查！</div>
            <div style={{ color: 'var(--error-color)', textAlign: 'left' }}>请注意：扫码时必须使用英文输入法。</div>
          </div>,
        )
      } else {
        const instance = Modal.warning({
          title: '提示',
          content: (
            <div>
              <div>商品条码不一致，请检查！</div>
              <div style={{ color: 'var(--error-color)' }}>请注意：扫码时必须使用英文输入法。</div>
            </div>
          ),
          okText: '关闭',
          icon: <ExclamationCircleOutlined />,
          onOk: () => {
            hasError && instance.destroy()
            inputRef?.current?.focus()
          },
        })
      }
      return
    }
    setinputValue('')
    if (flag) {
      const result = await tempSaveBoxPaking({
        boxLabelId,
        scannedQty: details.scannedQty ? details.scannedQty : 0,
      })
      if (result.code === 200) {
        message.success('操作成功')
        if (from) {
          navigate(from)
        } else {
          navigate('/scan/packing/list')
        }
      }
    } else {
      audioSuccess.currentTime = 0
      hasVoice && audioSuccess.play()
      // 判断是点数扫码还是一件多码
      if (ismanyshow) {
        //一件多码
        const nowhasScanPreQty = hasScanPreQty + 1
        if (nowhasScanPreQty == preQty) {
          calcNums(1)
          sethasScanPreQty(0)
        } else {
          sethasScanPreQty(nowhasScanPreQty)
        }
      } else {
        //逐件扫码或点数扫码
        calcNums(scannedQty)
      }
    }
  }

  const calcNums = (scannedQty: number) => {
    if (scannedQty + (details.scannedQty ? details.scannedQty : 0) > details.preloadQty) {
      message.warning('超出预装数量')
      return
    }
    const newDetails = {
      ...details,
      scannedQty: scannedQty + (details.scannedQty ? details.scannedQty : 0),
    }
    if (scannedQty + (details.scannedQty ? details.scannedQty : 0) == details.preloadQty) {
      checkIsOver(newDetails)
    }
    setDetail(newDetails)
  }
  const checkIsOver = async (details: Record<string, any>) => {
    if ((details.scannedQty || 0) === details.preloadQty) {
      handleOverPaking(details)
    }
  }
  const handleOverPaking = async (details: Record<string, any>) => {
    const text =
      (details.scannedQty || 0) === details.preloadQty
        ? '装箱完成，确认装箱吗？'
        : details.boxLabelType === null
        ? '未满箱将自动生成尾箱，确认装箱吗？'
        : '装箱完成，确认装箱吗？'
    const instance = Modal.confirm({
      title: '提示',
      content: text,
      okText: '确认',
      cancelText: '取消',
      icon: <ExclamationCircleOutlined />,
      onOk: async () => {
        const res = await scanAndPacking({
          boxLabelId,
          scannedQty: details.scannedQty ? details.scannedQty : 0,
        }).finally(() => instance.destroy())
        if (res.code === 200) {
          message.success('操作成功')
          if (from) {
            navigate(from)
          } else {
            navigate('/scan/packing/list')
          }
        }
      },
      onCancel() {
        console.log('Cancel')
      },
    })
  }
  return (
    <PageContainer className="purchase_packing_page">
      <div className="ppp_header_title">向箱子里添加商品</div>
      <CustomTable
        columns={usePakingColumns()}
        dataSource={[details]}
        pagination={null}
        rowKey={(rows) => rows.boxLabelId}
      />
      <div className="operation_box">
        <div className="operation_box_left">
          <Radio.Group
            options={radioOptions}
            optionType="button"
            value={defaultKey}
            onChange={(event) => {
              setdefaultKey(event.target.value)
              setscannedQty(1)
              setpreQty(2)
              if (event?.target.value == 'OneByOne') {
                setisshow(false)
                setismanyshow(false)
              } else if (event?.target.value == 'PointScan') {
                setisshow(true)
                setismanyshow(false)
              } else if (event?.target.value == 'MultiCodeScan') {
                setisshow(false)
                setismanyshow(true)
              }
            }}
          ></Radio.Group>
          {isshow ? (
            <div className="operation_input">
              <Typography.Text>扫一件算</Typography.Text>
              <Typography.Text>
                <InputNumber
                  className="ckbox_input_style"
                  precision={0}
                  defaultValue={scannedQty}
                  min={1}
                  onChange={(val) => setscannedQty(val ? val : 1)}
                ></InputNumber>
              </Typography.Text>
              <Typography.Text>件</Typography.Text>
            </div>
          ) : null}
          {ismanyshow ? (
            <div className="operation_input">
              <Typography.Text>扫</Typography.Text>
              <Typography.Text>
                <InputNumber
                  className="ckbox_input_style"
                  precision={0}
                  defaultValue={preQty}
                  min={2}
                  onChange={(val) => setpreQty(val ? val : 2)}
                ></InputNumber>
              </Typography.Text>
              <Typography.Text>算一件</Typography.Text>
            </div>
          ) : null}
          <div style={{ marginLeft: 12 }}>
            <Checkbox checked={hasVoice} onChange={(event) => sethasVoice(event.target.checked)}>
              声音提醒
            </Checkbox>
            <Checkbox checked={hasError} onChange={(event) => sethasError(event.target.checked)}>
              错误弹窗
            </Checkbox>
          </div>
        </div>
      </div>
      <div className="scan_goods_wrap">
        <div className="sgw_left">
          <div className="sgwwl_title">商品条码</div>
          <div className="operation_box_right">
            {'\u{26A0}\u{FE0F}'}：请将系统输入法切换至英文，避免扫码枪识别异常！
          </div>
          <div className="sgwwl_main">
            <Input
              autoFocus
              ref={inputRef}
              placeholder="--请扫码--"
              onChange={handleInputChange}
              value={inputValue}
              onPressEnter={() => handleSaveToList(false)}
            ></Input>
          </div>
          <div className="sgwwl_actions">
            <Space>
              <Button
                type="primary"
                onClick={() => handleOverPaking(details)}
                disabled={(details?.scannedQty || 0) == 0}
              >
                确认装箱
              </Button>
              <Button
                onClick={() => {
                  Modal.confirm({
                    title: '提示',
                    content: '确认要暂存吗？',
                    okText: '确认',
                    cancelText: '取消',
                    icon: <ExclamationCircleOutlined />,
                    onOk: () => handleSaveToList(true),
                  })
                }}
              >
                暂存
              </Button>
              {/* <Button
                onClick={() => {
                  Modal.confirm({
                    title: '提示',
                    content: '确认要取消吗？',
                    okText: '确认',
                    cancelText: '取消',
                    icon: <ExclamationCircleOutlined />,
                    onOk: () => navigate(-1),
                  })
                }}
              >
                取消
              </Button> */}
            </Space>
          </div>
        </div>
        {ismanyshow && (
          <div className="sgw_right">
            <div className="sgwr_text">已扫条码 / 单件条码</div>
            <div className="sgwr_num">
              {hasScanPreQty} / {preQty}
            </div>
          </div>
        )}
        <div className="sgw_right">
          <div className="sgwr_text">已装数量 / 预装数量</div>
          <div className="sgwr_num">
            {details.scannedQty || 0} / {details.preloadQty || 1}
          </div>
        </div>
      </div>
    </PageContainer>
  )
}

function PackingNumber() {
  const [val, setVal] = useState('')
  const navigate = useNavigate()
  const hanldleGetInfo = async () => {
    if (!val) {
      message.warning('请扫描箱唛条码！')
      return
    }
    const res = await scanAndGetInfo<Record<string, any>>(val)
    if (res.code === 200) {
      if (res.data?.boxLabelId) {
        if (res.data.boxLabelStatus == 3) {
          navigate('/scan/packing/list?boxLabelId=' + res.data?.boxLabelId + '&boxLabelCode=' + res.data?.boxLabelCode)
        } else {
          message.warning('当前箱唛不是待装箱状态！')
        }
      } else {
        message.warning('未查询到该箱唛条码信息，请确认箱唛条码是否正确！')
      }
    }
  }
  return (
    <PageContainer className="purchase_packing_number">
      <div className="scan_goods_wrap">
        <div className="sgw_left">
          <div className="sgwwl_title">箱唛条码</div>
          <div className="sgwwl_main">
            <Input
              autoFocus
              placeholder="--请扫码--"
              onChange={(event: any) => setVal(event.target.value)}
              value={val}
              onPressEnter={hanldleGetInfo}
            ></Input>
          </div>
          <div className="sgwwl_actions">
            <Space>
              <Button type="primary" onClick={hanldleGetInfo}>
                确认
              </Button>
            </Space>
          </div>
        </div>
      </div>
    </PageContainer>
  )
}
